package com.example.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.BCrypt;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.entity.User;
import com.example.dto.LoginRequest;
import com.example.dto.RegisterRequest;
import com.example.dto.UserInfoResponse;
import com.example.service.UserService;
import com.example.mapper.UserMapper;
import com.example.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
* @author Administrator
* @description 针对表【user】的数据库操作Service实现
* @createDate 2025-06-02 15:49:32
*/
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public String register(RegisterRequest registerRequest) {
        // 检查用户名是否已存在
        User existingUser = findByUsername(registerRequest.getUsername());
        if (existingUser != null) {
            throw new RuntimeException("用户名已存在");
        }

        // 创建新用户
        User user = new User();
        user.setUsername(registerRequest.getUsername());
        // 使用BCrypt加密密码
        user.setPassword(BCrypt.hashpw(registerRequest.getPassword()));

        // 保存用户
        int result = userMapper.insert(user);
        if (result > 0) {
            return "注册成功";
        } else {
            throw new RuntimeException("注册失败");
        }
    }

    @Override
    public String login(LoginRequest loginRequest) {
        // 查找用户
        User user = findByUsername(loginRequest.getUsername());
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        // 验证密码
        if (!BCrypt.checkpw(loginRequest.getPassword(), user.getPassword())) {
            throw new RuntimeException("密码错误");
        }

        // 生成JWT token
        return jwtUtil.generateToken(user.getId(), user.getUsername());
    }

    @Override
    public UserInfoResponse getUserInfo(Long userId) {
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        return new UserInfoResponse(user.getId(), user.getUsername());
    }

    @Override
    public User findByUsername(String username) {
        if (StrUtil.isBlank(username)) {
            return null;
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        return userMapper.selectOne(queryWrapper);
    }

    @Override
    public Map<Long, UserInfoResponse> getUsersByIds(List<Long> userIds) {
        if (userIds == null || userIds.isEmpty()) {
            return new HashMap<>();
        }

        // 去重并过滤null值
        List<Long> validUserIds = userIds.stream()
                .filter(Objects::nonNull)
                .distinct()
                .collect(Collectors.toList());

        if (validUserIds.isEmpty()) {
            return new HashMap<>();
        }

        // 批量查询用户
        List<User> users = userMapper.selectBatchIds(validUserIds);

        // 转换为Map
        Map<Long, UserInfoResponse> userInfoMap = users.stream()
                .collect(Collectors.toMap(
                    User::getId,
                    user -> new UserInfoResponse(user.getId(), user.getUsername())
                ));

        return userInfoMap;
    }
}
